import { AppCTX } from "../../types/koaExtend";
import { createBrandApiMWRouter } from "../../middleware/brand-api/brandAdminChecker";
import pageMW from "../../middleware/pager";
import {
  getActivityOfB,
  createActivityOfB,
  updateActivityOfB,
  checkActivityOfBParamFields,
  pauseActivityOfB,
  resumeActivityOfB,
  publishActivityOfB,
  listActivityItemOfBWithStatsByBrandID,
} from "../../service/activityService";
import {
  AggsToActivityUserPvCount,
  listAggsToActivityUserPvCounts,
} from "../../service/activityUserPvLogService";
import { _pick, reduceToObject, isUndefined } from "mmb";
import { UpdateActivityOfBParams } from "../../service/declareTypes";
import ActivitySaleMode from "../../bg-enums/activitySaleMode";
import ActivityProcessStatus, {
  isActivityProcessStatus,
} from "../../bg-enums/activityProcessStatus";

const router = createBrandApiMWRouter();

// 获取品牌的活动列表(品牌管理视角)
router.get("/brd/:brandId/activities", pageMW, async (ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  let { isAll, processStatus, keyword } = ctx.query;
  const { userId, limit, offset, ts } = ctx;
  let arrProcessStatus: ActivityProcessStatus[] = [];
  if (!isUndefined(processStatus)) {
    for (let ps of processStatus.split(",")) {
      if (!isActivityProcessStatus(ps)) {
        ctx.throw(400, "processStatus invalid");
      }
      arrProcessStatus.push(ps);
    }
  }
  const { total, items } = await listActivityItemOfBWithStatsByBrandID(
    {
      brandId,
      isAll: isAll === "true",
      processStatuses: arrProcessStatus,
      keyword,
    },
    {
      limit,
      offset,
      ts,
    }
  );

  // const activityUserPvCounts = await listAggsToActivityUserPvCounts(
  //   items.map((it) => it.activityId)
  // );
  // const activityUserPvCountsMap = reduceToObject(
  //   activityUserPvCounts,
  //   (o: AggsToActivityUserPvCount) => o.activityId,
  //   (o: AggsToActivityUserPvCount) => o.viewCount
  // );

  ctx.body = {
    total,
    rows: items,
  };
});

// 获取品牌活动详情(品牌管理视角)
router.get("/brd/:brandId/activity/:activityId", async (ctx: AppCTX, next) => {
  const { brandId, activityId } = ctx.params;
  const { userId } = ctx;

  const activity = await getActivityOfB(activityId);
  if (activity.brandId !== brandId) {
    ctx.throw(400, "no belong current brand");
  }

  ctx.body = {
    ...activity,
  };
});

// 获取品牌活动的购买记录列表(品牌管理视角)
router.get(
  "/brd/:brandId/activity/:activityId/buyRecords",
  async (ctx: AppCTX, next) => {
    const { brandId, activityId } = ctx.params;
    const { userId } = ctx;
    ctx.body = {
      activityId,
      brandId,
      userId,
      buyRecords: [
        {
          orderId: (5123).toString(),
          ordered: Date.now(),
          items: [
            {
              itemInfo: { productName: "商品名称1", keyA: "a2", keyB: "b1" },
              quality: 1,
            },
          ],
        },
        {
          orderId: (5124).toString(),
          ordered: Date.now(),
          items: [
            {
              itemInfo: { productName: "商品名称1", keyA: "a1", keyB: "b1" },
              quality: 1,
            },
          ],
        },
      ],
    };
  }
);

// 新增品牌活动
router.post("/brd/:brandId/activity", async (ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  const { userId } = ctx;
  const {
    type,
    name,
    intro,
    begined,
    ended,
    timeRanges,
    background,
    checkIn1,
    lottery1,
    saleMode,
    deliveryModes,
    isUseWarehouseShippingFeeRule,
    unifiedShippingFee,
    minimumPurchaseAmount,
    tel,
    // warehouses
    warehouseIds,
    // productWithSkus
    activityProductWithSkus,
    // consignment
  } = ctx.request.body;
  let { consignment, maxiumPurchaseFrequency } = ctx.request.body;

  if (saleMode === ActivitySaleMode.ONLY_BRAND_SELLING) {
    consignment = {
      allowHiddenProduct: false,
      allowAllSpokesman: false,
      consignmentBonusSettings: [],
      specificSpokesmanIds: [],
    };
  }

  // check params
  checkActivityOfBParamFields({
    type,
    intro,
    begined,
    ended,
    timeRanges,
    checkIn1,
    lottery1,
    saleMode,
    deliveryModes,
    isUseWarehouseShippingFeeRule,
    unifiedShippingFee,
    maxiumPurchaseFrequency,
    warehouseIds,
    activityProductWithSkus,
    consignment,
  });
  if (maxiumPurchaseFrequency === 0) {
    maxiumPurchaseFrequency = undefined;
  }

  const activity = await createActivityOfB({
    brandId,
    pubUserId: userId,
    type,
    name,
    intro,
    begined,
    ended,
    timeRanges,
    background,
    checkIn1,
    lottery1,
    saleMode,
    deliveryModes,
    isUseWarehouseShippingFeeRule,
    unifiedShippingFee,
    maxiumPurchaseFrequency,
    minimumPurchaseAmount,
    tel,
    // warehouses
    warehouseIds,
    // productWithSkus
    activityProductWithSkus,
    // consignment
    consignment,
  });

  ctx.body = {
    ...activity,
  };
});

// 更新品牌活动
router.put("/brd/:brandId/activity/:activityId", async (ctx: AppCTX, next) => {
  const { brandId, activityId } = ctx.params;
  const { userId } = ctx;
  const {
    type,
    name,
    intro,
    begined,
    ended,
    timeRanges,
    background,
    checkIn1,
    lottery1,
    saleMode,
    deliveryModes,
    isUseWarehouseShippingFeeRule,
    unifiedShippingFee,
    minimumPurchaseAmount,
    tel,
    warehouseIds,
    activityProductWithSkus,
  } = ctx.request.body;
  let { consignment, maxiumPurchaseFrequency } = ctx.request.body;

  if (saleMode === ActivitySaleMode.ONLY_BRAND_SELLING) {
    consignment = {
      allowHiddenProduct: false,
      allowAllSpokesman: false,
      consignmentBonusSettings: [],
      specificSpokesmanIds: [],
    };
  }

  checkActivityOfBParamFields(
    {
      type,
      intro,
      begined,
      ended,
      timeRanges,
      checkIn1,
      lottery1,
      saleMode,
      deliveryModes,
      isUseWarehouseShippingFeeRule,
      unifiedShippingFee,
      maxiumPurchaseFrequency,
      warehouseIds,
      activityProductWithSkus,
      consignment,
    },
    false
  );

  if (maxiumPurchaseFrequency === 0) {
    maxiumPurchaseFrequency = undefined;
  }
  let p: UpdateActivityOfBParams = {
    type,
    activityId,
    name,
    intro,
    begined,
    ended,
    timeRanges,
    background,
    checkIn1,
    lottery1,
    saleMode,
    deliveryModes,
    isUseWarehouseShippingFeeRule,
    unifiedShippingFee,
    maxiumPurchaseFrequency,
    minimumPurchaseAmount,
    tel,
    // warehouses
    warehouseIds,
    // productWithSkus
    activityProductWithSkus,
    // consignment
    consignment,
  };

  // mark 迁移到 bgs
  // let activity = await getActivityOfB(activityId);
  // const inventoryFreezeNo = activity.inventoryFreezeNo;
  // if (!isUndefined(inventoryFreezeNo) && activity.ended > Date.now()) {
  //   ctx.throw(400, "当前不允许")
  //   const warehouseId = activity.warehouseIds[0];
  //   const warehouseRemotePk = await getBrandWarehouseRemotePkCachelly(
  //     warehouseId
  //   );
  //   let details: FreezeOrderOfBForActivityDetailParams[] = [];

  //   activityProductWithSkus.forEach((a: ActivityProductWithSku) => {
  //     details.push(
  //       ...a.skus.map((s) => ({
  //         warehouseRemotePk,
  //         storageKey: s.storageKey,
  //         quantity: s.quantity,
  //         storageName: `${a.productName}(${s.skuName})`,
  //       }))
  //     );
  //   });
  //   const webposToken = await getBrandWebTokenSafely(brandId);
  //   await updateFreezeOrderForActivity(webposToken)({
  //     orderNumber: inventoryFreezeNo,
  //     activityId,
  //     activityEnded: activity.ended,
  //     details,
  //   });
  //   console.log("更新仓库冻结单成功=>", JSON.stringify(inventoryFreezeNo));
  // }

  let activity = await updateActivityOfB(p);

  ctx.body = {
    ...activity,
  };
});

// 暂停品牌活动
router.put(
  "/brd/:brandId/activity/:activityId/pause",
  async (ctx: AppCTX, next) => {
    const { brandId, activityId } = ctx.params;
    const { userId } = ctx;
    const processStatus = await pauseActivityOfB({ activityId, brandId });
    ctx.body = {
      activityId,
      processStatus,
    };
  }
);

// 恢复品牌活动
router.put(
  "/brd/:brandId/activity/:activityId/resume",
  async (ctx: AppCTX, next) => {
    const { brandId, activityId } = ctx.params;
    const { userId } = ctx;
    const processStatus = await resumeActivityOfB({ activityId, brandId });
    ctx.body = {
      activityId,
      processStatus,
    };
  }
);

// 发布品牌活动
router.put(
  "/brd/:brandId/activity/:activityId/publish",
  async (ctx: AppCTX, next) => {
    const { brandId, activityId } = ctx.params;
    const { userId } = ctx;
    // const brand = await getBrand(brandId);

    // const activity = await getActivityOfB(activityId);
    // const warehouseId = activity.warehouseIds[0];
    // const brandRemotePk = await getBrandRemotePkCachelly(brandId);
    // const warehouseRemotePk = await getBrandWarehouseRemotePkCachelly(
    //   warehouseId
    // );

    // let details: FreezeOrderOfBForActivityDetailParams[] = [];

    // activity.activityProductWithSkus.forEach((a) => {
    //   console.log("details=>", a.skus);
    //   details.push(
    //     ...a.skus.map((s) => ({
    //       warehouseRemotePk,
    //       storageKey: s.storageKey,
    //       quantity: s.quantity,
    //       storageName: `${a.productName}(${s.skuName})`,
    //     }))
    //   );
    // });
    // const webposToken = await getBrandWebTokenSafely(brandId);
    // const p = await createFreezeOrderForActivity(webposToken)({
    //   brandRemotePk,
    //   activityId,
    //   activityEnded: activity.ended,
    //   remark: activity.name,
    //   details,
    //   orderKey: userId,
    // });
    // console.log("publishActivityOfB params=>", JSON.stringify(p));

    const processStatus = await publishActivityOfB({ activityId, userId });
    ctx.body = {
      activityId,
      processStatus,
    };
  }
);

export default router;
